//
//  AIGirlHomeViewController.swift
//  AIGirl
//
//  Created by Rae on 2023/12/22.
//

import UIKit
import SwiftyStoreKit

class AIGirlHomeViewController: AIGirlBaseViewController {
    
    private var navView = AIGirlHomeNavView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    private var dataSource: AIGirlHomeModel?
    private var rechargeList = [AIGirlHomeItemModel]()
    
    private var topViewH = 440.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        view.subviews {
            navView
            collectionView
        }
        
        navView.leading(0).trailing(0).top(.statusHeight).height(44.0)
        collectionView.leading(0).trailing(0).top(.navi_height).bottom(0)
        
        navView.title = "AI Girl"
        
        let w = (.screenWidth - 35) / 2
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.sectionInset = UIEdgeInsets(top: 0, left: 10.0, bottom: 0, right: 10.0)
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: w, height: 180.0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlDiamondItem.self, forCellWithReuseIdentifier: AIGirlDiamondItem.description())
            v.register(AIGirlHomeTopView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: AIGirlHomeTopView.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        if GlobalTool.userModel?.isVip.intValue ?? 0 > 0 {
            topViewH = 335.0
        }else{
            topViewH = 440.0
        }
        NotificationCenter.default.addObserver(forName: .updateVIPState, object: nil, queue: nil) { noti in
            if GlobalTool.userModel?.isVip.intValue ?? 0 > 0 {
                self.topViewH = 335.0
            }else{
                self.topViewH = 440.0
            }
            self.collectionView.reloadData()
        }
        loadData()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            if let coins = UserDefaultsManager.getString(forKey: .sendCoin), coins.count > 0 {
                if coins != "0" {
                    UserDefaultsManager.setInt(0, forKey: .isShowFirstAward)
                    UserDefaultsManager.removeForKey(forKey: .sendCoin)
                    let firstV = AIGirlLoginAwardView()
                    firstV.value = Int(coins) ?? 0
                    self.animation.animation(show: firstV)
                }
            }
        }
    }
    
    private func loadData(){
        
        request.start(.rechargeList(needActivityRechargeTypes: "recommendRecharge"),type: AIGirlHomeModel.self) { result in
            if result.isSuccessful, let model = result.model {
                self.dataSource = model
                var dataArr = model.rechargeList
                dataArr.sort{$0.sortTop < $1.sortTop}
                self.rechargeList = dataArr
                self.collectionView.reloadData()
            }
            
        }
        request.start(.loginAward,type: AIGirlAwardModel.self,isLoading: false) { result in
            
            if result.isSuccessful, let md = result.model {
                
                let value = md.value
                if value != 0 {
                    let isShow = UserDefaultsManager.getInt(forKey: .isShowFirstAward)
                    if isShow == 99 {
                        UserDefaultsManager.setInt(0, forKey: .isShowFirstAward)
                        let firstV = AIGirlLoginAwardView()
                        firstV.value = value
                        self.animation.animation(show: firstV)
                    }else{
                        let firstV = AIGirlLoginDailyAwardView()
                        firstV.value = value
                        self.animation.animation(show: firstV)
                    }
                }
            }
        }
//        request.start(.initConfig,type: AIGirlConfigModel.self) { result in
//            
//            if result.isSuccessful, let model = result.model {
//                
//                
//            }
//        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        GlobalTool.refreshUserInfo { [weak self] in
            let money = GlobalTool.userModel?.money ?? 0
            self?.navView.diamondButton.setTitle("\(money)", for: .normal)
            if GlobalTool.userModel?.isVip.intValue ?? 0 > 0 {
                self?.topViewH = 335.0
            }else{
                self?.topViewH = 440.0
            }
            self?.collectionView.reloadData()
        }
    }
}

extension AIGirlHomeViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return rechargeList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlDiamondItem.description(), for: indexPath) as? AIGirlDiamondItem else { return UICollectionViewCell() }
        var model = rechargeList[indexPath.row]
        model.index = indexPath.row
        item.model = model
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let model = rechargeList[indexPath.row]
        purchaseTool.purchaseProduct(productCode: model.code, productId: model.id)
    }
        
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: AIGirlHomeTopView.description(), for: indexPath) as! AIGirlHomeTopView
            // 根据需要自定义 header
            header.model = dataSource?.activityRecharge
            return header
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSize(width: .screenWidth, height: topViewH)
    }
}
